﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Cyss.Core;
using Common.Api.Services;
using Common.Api.Entitys;
using Common.Api.Dtos;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

namespace Common.Api.Controllers
{

    /// <summary>
    /// 获取文件表 Api 接口
    /// </summary>
    public class DownloadController : CommonBaseApiController
    {
        #region 初始化
        private readonly DownloadService _downloadService;

        public DownloadController(DownloadService downloadService)
        {
            _downloadService = downloadService;
        }
        #endregion

        #region 文件表增删该查

        [HttpGet]
        public virtual OperateResult<Download> GetDownloadById(int Id)
        {
            return OperateResultContent(true, _downloadService.FirstOrDefault(x => x.Id == Id));
        }

        [HttpGet]
        public virtual async Task<IActionResult> GetFileById(int Id)
        {
            var download = _downloadService.FirstOrDefault(x => x.Id == Id);
            if (download == null)
                return Content("No download record found with the specified id");

            var fileName = !string.IsNullOrWhiteSpace(download.FileName) ? download.FileName : download.Id.ToString();
            var contentType = !string.IsNullOrWhiteSpace(download.ContentType)
                ? download.ContentType
                : MimeTypes.ApplicationOctetStream;

            return new FileContentResult(await _downloadService.GetFielBytesAsync(download), contentType)
            {
                FileDownloadName = fileName + download.Extension
            };
        }



        [HttpPost]
        //do not validate request token (XSRF)
        public virtual async Task<OperateResult<Dtos.FileResult>> AsyncUpload([FromForm] IFormCollection formCollection)
        {
            var httpPostedFile = formCollection.Files.FirstOrDefault();
            if (httpPostedFile == null)
                return OperateResultContent<Dtos.FileResult>(false, null, "No file uploaded");

            var _fileProvider = new FileProvider();

            var fileBinary = await _fileProvider.GetDownloadBitsAsync(httpPostedFile);

            var qqFileNameParameter = "qqfilename";
            var fileName = httpPostedFile.FileName;
            if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter))
                fileName = Request.Form[qqFileNameParameter].ToString();
            //remove path (passed in IE)
            fileName = _fileProvider.GetFileName(fileName);

            var contentType = httpPostedFile.ContentType;

            var fileExtension = _fileProvider.GetFileExtension(fileName);
            if (!string.IsNullOrEmpty(fileExtension))
                fileExtension = fileExtension.ToLowerInvariant();

            var download = new Download
            {
                ContentType = contentType,
                MimeType = string.Empty,
                SeoFilename = string.Empty,
                AltAttribute = string.Empty,
                TitleAttribute = string.Empty,
                Size = fileBinary.LongLength,
                CreateDateTime = DateTime.Now,
                FileName = _fileProvider.GetFileNameWithoutExtension(fileName),
                Extension = fileExtension,
                IsNew = true
            };
            download.SetDefaultValue();
            await _downloadService.InsertFile(download, fileBinary);
            return OperateResultContent(true, new Dtos.FileResult { FileId = download.Id });
        }


        #endregion
    }
}




